<template>
  <div class="layout-container">
    <div class="back-header">
      <el-page-header title="返回" :content="pageHeader" @back="goBack" />
    </div>
    <el-form
      ref="refruleForm"
      :model="form"
      :rules="rules"
      label-width="130px"
      style="width: 50%; min-width: 463px; margin: 100px auto"
    >
      <el-form-item label="管理员账号：" prop="user_name">
        <el-input
          v-model="form.user_name"
          placeholder="请输入管理员姓名"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="管理员昵称：" prop="nick_name">
        <el-input
          v-model="form.nick_name"
          placeholder="请输入管理员昵称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="密码：" prop="pass_word">
        <el-input
          :type="inputType"
          v-model.trim="form.pass_word"
          class="input-pwd"
          :placeholder="
            editAdminInfo.Id
              ? '编辑状态下密码如果为空说明不修改密码'
              : '请输入密码'
          "
          @focus="setInputType"
        />
      </el-form-item>
      <el-form-item label="管理员类型：" prop="admin_type">
        <el-select
          v-model="form.admin_type"
          placeholder="请选择管理员类型"
          style="width: 100%"
        >
          <el-option
            v-for="item in typeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态：" prop="status">
        <el-select
          v-model="form.status"
          placeholder="请选择状态"
          style="width: 100%"
        >
          <el-option
            v-for="item in statusOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="项目权限："
        prop="project_permissions"
        v-if="form.admin_type == 2"
      >
        <el-select
          v-model="form.project_permissions"
          placeholder="请选择项目权限"
          style="width: 100%"
          multiple
          filterable
          remote
          reserve-keyword
          :remote-method="projectRemoteMethod"
        >
          <el-option
            v-for="item in projectAuthOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="团队权限："
        prop="team_permissions"
        v-if="form.admin_type == 2"
      >
        <el-select
          v-model="form.team_permissions"
          placeholder="请选择项目权限"
          style="width: 100%"
          multiple
          filterable
          remote
          reserve-keyword
          :remote-method="teamRemoteMethod"
        >
          <el-option
            v-for="item in teamAuthOptions"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="查看权限："
        prop="action_permissions"
        v-if="form.admin_type == 2"
      >
        <el-select
          v-model="form.action_permissions"
          placeholder="请选择项目权限"
          style="width: 100%"
          multiple
        >
          <el-option
            v-for="item in authOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button style="width: 160px" @click="handleCancel">取消</el-button>
        <el-button
          style="width: 160px"
          type="primary"
          :loading="subLoading"
          @click="handleSubmit"
          >保存</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import md5 from "js-md5";
import { defineComponent, ref, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "vuex";
import {
  createSystemAdmin,
  editSystemAdmin,
  getAuthList,
} from "@/api/service/user.ts";
import { regPwd } from "@/utils/reg.ts";
const router = useRouter();
const route = useRoute();
const { state } = useStore();
const pageHeader = ref("新建管理员");
// console.log(state.user.editAdminInfo);
const editAdminInfo = reactive(state.user.editAdminInfo);
const refruleForm: any = ref(null);
if (editAdminInfo.Id) {
  pageHeader.value = "编辑管理员账号";
}

const inputType = ref('text');
// const setInputType = () => {
//   inputType.value = 'password'
// };

const form: any = reactive({
  id: editAdminInfo.Id ? editAdminInfo.Id : undefined,
  action_permissions: editAdminInfo.action_permissions
    ? editAdminInfo.action_permissions
    : [], // array[string] 操作权、 "0" 全部权限 1查看权限 2上传权限 3 下载权限
  admin_type:
    editAdminInfo.admin_type != null ? editAdminInfo.admin_type : undefined, // integer
  pass_word: editAdminInfo.pass_word, // string
  project_permissions: editAdminInfo.project_permissions
    ? editAdminInfo.project_permissions
    : [], // array[string] 项目权限
  status: editAdminInfo.status != null ? editAdminInfo.status : undefined, // integer
  team_permissions: editAdminInfo.team_permissions
    ? editAdminInfo.team_permissions
    : [], // array[string] 团队权限
  user_name: editAdminInfo.user_name, // string
  nick_name: editAdminInfo.nick_name,
});
// 管理员类型
const typeOptions = ref([
  // {
  //   id: '0',
  //   name: '系统管理员'
  // },
  {
    id: 1,
    name: "副管理员",
  },
  {
    id: 2,
    name: "子管理员",
  },
]);
// 状态
const statusOptions = ref([
  {
    id: 1,
    name: "正常",
  },
  {
    id: 0,
    name: "封禁",
  },
]);
// 权限
const authOptions = ref([
  {
    id: "1",
    name: "查看权限",
  },
  {
    id: "2",
    name: "上传权限",
  },
  {
    id: "3",
    name: "下载权限",
  },
]);

// 必填校验
const rules = reactive({
  user_name: [
    {
      required: true,
      message: "请输入管理员姓名",
      trigger: "blur",
    },
  ],
  nick_name: [
    {
      required: true,
      message: "请输入管理员昵称",
      trigger: "blur",
    },
  ],
  pass_word: [
    {
      required: editAdminInfo.Id ? false : true,
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        let reg = regPwd;
        if (value && !reg.test(value)) {
          return callback(new Error("密码长度至少8位，密码含有数字和字母"));
        } else if (!value && !editAdminInfo.Id) {
          return callback(new Error("请输入密码"));
        } else {
          return callback();
        }
      },
    },
  ],
  status: [
    {
      required: true,
      message: "请选择状态",
      trigger: "change",
    },
  ],
  admin_type: [
    {
      required: true,
      message: "请选择管理员类型",
      trigger: "change",
    },
  ],
  // project_permissions: [
  //   {
  //     required: true,
  //     message: "请选择项目权限",
  //     trigger: "change",
  //   },
  // ],
  // team_permissions: [
  //   {
  //     required: true,
  //     message: "请选择团队权限",
  //     trigger: "change",
  //   },
  // ],
  // action_permissions: [
  //   {
  //     required: true,
  //     message: "请选择查看权限",
  //     trigger: "change",
  //   },
  // ],
});

// 返回
const goBack = () => {
  router.push({
    path: "/backstagerpzzm/accountManagement/adminAccessManagement",
  });
};
// 取消
const handleCancel = () => {
  router.push({
    path: "/backstagerpzzm/accountManagement/adminAccessManagement",
  });
};
// 保存
const handleSubmit = () => {
  refruleForm.value.validate((valid: Boolean) => {
    if (valid) {
      createSystemAdminFun();
    } else {
      console.log("error submit!!");
      return false;
    }
  });
};
const subLoading = ref(false);
const createSystemAdminFun = () => {
  subLoading.value = true;
  let data = {
    id: form.id,
    action_permissions: form.action_permissions, // array[string] 操作权、 "0" 全部权限 1查看权限 2上传权限 3 下载权限
    admin_type: form.admin_type, // integer
    pass_word: form.pass_word ? md5(form.pass_word) : undefined, // string
    project_permissions: form.project_permissions, // array[string] 项目权限
    status: form.status, // integer
    team_permissions: form.team_permissions, // array[string] 团队权限
    user_name: form.user_name, // string
    nick_name: form.nick_name,
  };
  if (editAdminInfo.Id) {
    //id存在编辑
    editSystemAdmin(data)
      .then((res: any) => {
        if (res.code === 200) {
          ElMessage.success("保存成功");
          setTimeout(() => {
            router.go(-1);
          }, 1000);
        }
      })
      .finally(() => {
        subLoading.value = false;
      });
  } else {
    createSystemAdmin(data)
      .then((res: any) => {
        if (res.code === 200) {
          ElMessage.success("保存成功");
          setTimeout(() => {
            router.go(-1);
          }, 1000);
        }
      })
      .finally(() => {
        subLoading.value = false;
      });
  }
};

// 获取项目权限
const projectAuthOptions = ref([]);
// 获取团队权限
const teamAuthOptions = ref([]);
const getAuthListFun = (tp: Number, search_text: String) => {
  let data = {
    search_text: search_text,
    tp: tp, // 0：项目 1：团队
  };
  getAuthList(data).then((res: any) => {
    if (res.code === 200) {
      if (tp === 0) {
        projectAuthOptions.value = res.data;
      } else {
        teamAuthOptions.value = res.data;
      }
    }
  });
};
getAuthListFun(0, "");
getAuthListFun(1, "");
const projectRemoteMethod = (val: any) => {
  getAuthListFun(0, val);
};
const teamRemoteMethod = (val: any) => {
  getAuthListFun(1, val);
};
</script>

<style lang="scss" scoped>
.layout-container {
  height: auto;
  .back-header {
    padding: 20px;
    width: 100%;
    border-bottom: 1px solid #fafafa;
  }
  .input-pwd{
    text-security:disc;
    -webkit-text-security:disc;
    -mox-text-security:disc;
  }
}
</style>
